import { Body, Controller, Post, Get, Res, Headers, Req } from '@nestjs/common';
import { WipAlarmRecordService } from './alarmRecord.service';
import { ADMIN_PREFIX } from '../../admin.constants';
import { ApiOkResponse, ApiOperation, ApiSecurity, ApiTags } from '@nestjs/swagger';
import { AdminUser } from '../../core/decorators/admin-user.decorator';
import i18n from '@main/i18n';
import { format } from 'date-fns';
import { Authorize } from '../../core/decorators/authorize.decorator';
import { FastifyRequest } from 'fastify';

@ApiSecurity(ADMIN_PREFIX)
@ApiTags('报警记录管理模块')
@Controller('alarmRecord')
export class WipAlarmRecordController {
  constructor(private wipAlarmRecordService: WipAlarmRecordService) {}

  @ApiOperation({ summary: '获取报警记录列表' })
  @ApiOkResponse()
  @Get('list')
  async list() {
    return await this.wipAlarmRecordService.list();
  }

  @ApiOperation({ summary: '分页获取报警记录列表' })
  @ApiOkResponse()
  @Post('page')
  async page(@Body() dto, @Headers('language') languageType) {
    const [list, total] = await this.wipAlarmRecordService.page(dto, languageType);

    return {
      list,
      pagination: {
        total,
        pageNum: dto.pageNum,
        pageSize: dto.pageSize,
      },
    };
  }

  @ApiOperation({ summary: '添加报警记录' })
  @ApiOkResponse()
  @Post('add')
  async add(@Body() dto, @AdminUser() user, @Req() req: FastifyRequest) {
    const { mac = '', ip = '', synchostsqlite: syncHostSqlite = '' } = req.headers;
    await this.wipAlarmRecordService.add(dto, user, mac, ip, syncHostSqlite);
  }

  @ApiOperation({ summary: '更新报警记录' })
  @ApiOkResponse()
  @Authorize()
  @Post('update')
  async update(@Body() dto, @AdminUser() user, @Req() req: FastifyRequest) {
    const { mac = '', ip = '', synchostsqlite: syncHostSqlite = '' } = req.headers;
    await this.wipAlarmRecordService.update(dto, user, mac, ip, syncHostSqlite);
  }

  @ApiOperation({ summary: '导出报警记录' })
  @ApiOkResponse()
  @Post('export')
  async export(@Body() dto, @Res() res, @Headers('language') languageType) {
    const buffer = await this.wipAlarmRecordService.export(dto, languageType);

    const langObj = i18n[languageType]['common']['table'];

    res.header('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');

    res.header(
      'Content-Disposition',
      `attachment; filename=${encodeURIComponent(
        langObj['alarmRecord'] + format(new Date(), 'yyyyMMddHHmmss') + '.xlsx'
      )}`
    );

    res.header('Access-Control-Expose-Headers', 'Content-Disposition');

    res.send(buffer);
  }
}
